/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package tk.mybatis.mapper.generator;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.CommentGeneratorConfiguration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.internal.util.StringUtility;

/**
 * 通用Mapper生成器插件
 *
 * @author liuzh
 */
public class MapperPlugin extends PluginAdapter {
    private Set<String> mappers = new HashSet<String>();
    private boolean caseSensitive = false;

    @Override
    public void setContext(Context context) {
        super.setContext(context);
        //设置默认的注释生成器
        CommentGeneratorConfiguration commentCfg = new CommentGeneratorConfiguration();
        commentCfg.setConfigurationType(MapperCommentGenerator.class.getCanonicalName());
        context.setCommentGeneratorConfiguration(commentCfg);
    }

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
        String mappers = this.properties.getProperty("mappers");
        if (StringUtility.stringHasValue(mappers)) {
            for (String mapper : mappers.split(",")) {
                this.mappers.add(mapper);
            }
        } else {
            throw new RuntimeException("Mapper插件缺少必要的mappers属性!");
        }
        String caseSensitive = this.properties.getProperty("caseSensitive");
        if (StringUtility.stringHasValue(caseSensitive)) {
            this.caseSensitive = caseSensitive.equalsIgnoreCase("TRUE");
        }
    }

    @Override
    public boolean validate(List<String> warnings) {
    	for (String string : warnings) {
			System.out.println(string);
		}
        return true;
    }

    /**
     * 生成的Mapper接口
     *
     * @param interfaze
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        //获取实体类
        FullyQualifiedJavaType entityType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        //import接口
        for (String mapper : mappers) {
            interfaze.addImportedType(new FullyQualifiedJavaType(mapper));
            interfaze.addSuperInterface(new FullyQualifiedJavaType(mapper + "<" + entityType.getShortName() + ">"));
        }
        //import实体类
        interfaze.addImportedType(entityType);
        return true;
    }

    private void generateToString(IntrospectedTable introspectedTable,
			TopLevelClass topLevelClass) {
//		Method method = new Method();
//		method.setVisibility(JavaVisibility.PUBLIC);
//		method.setReturnType(FullyQualifiedJavaType.getStringInstance());
//		method.setName("toString");
//		if (introspectedTable.isJava5Targeted())
//			method.addAnnotation("@Override");
//		context.getCommentGenerator().addGeneralMethodComment(method,
//				introspectedTable);
//		method.addBodyLine("StringBuilder sb = new StringBuilder();");
//		method.addBodyLine("sb.append(getClass().getSimpleName());");
//		method.addBodyLine("sb.append(\" [\");");
//		method.addBodyLine("sb.append(\"Hash = \").append(hashCode());");
//		StringBuilder sb = new StringBuilder();
//		for (Iterator<Field> i$ = topLevelClass.getFields().iterator(); i$.hasNext();) {
//			Field field = (Field) i$.next();
//			if(field.isFinal() && field.isStatic()) {
//				continue;
//			}
//			if(sb.length() > 0)
//				method.addBodyLine(sb.toString());
//			String property = field.getName();
//			sb.setLength(0);
//			sb.append("sb.append(\"").append(", ").append(property)
//					.append("=\")").append(".append(").append(property)
//					.append(");");
//		}
//
//		method.addBodyLine("sb.append(\"]\");");
//		method.addBodyLine("return sb.toString();");
//		topLevelClass.addMethod(method);
	}
    /**
     * 处理实体类的包和@Table注解
     *
     * @param topLevelClass
     * @param introspectedTable
     */
    private void processEntityClass(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
    	
        //引入JPA注解
        topLevelClass.addImportedType("javax.persistence.*");
        topLevelClass.addImportedType("com.ag.core.base.Domain");
        
        topLevelClass.addJavaDocLine("/**");
        String catalog = introspectedTable.getTableConfiguration().getCatalog();
        if(StringUtils.isBlank(catalog)) {
        	catalog = "数据库实体";
        }
    	StringBuilder sb = new StringBuilder();
    	sb.append(" * \n");
    	sb.append(" * @title:" + catalog + "\n");
    	sb.append(" * " + introspectedTable.getBaseRecordType() + "\n");
    	sb.append(" * \n");
    	sb.append(" * @author rplees" + "\n");
    	sb.append(" * @email rplees.i.ly@gmail.com" + "\n");
    	sb.append(" * @created " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    	
    	topLevelClass.addJavaDocLine(sb.toString());
    	topLevelClass.addJavaDocLine(" */");
    	
    	topLevelClass.setSuperClass(new FullyQualifiedJavaType("com.ag.core.base.Domain"));
    	
    	Field serialVersionUIDField = new Field();
    	serialVersionUIDField.setName("serialVersionUID");
    	serialVersionUIDField.setFinal(true);
    	serialVersionUIDField.setStatic(true);
    	serialVersionUIDField.setType(new FullyQualifiedJavaType("long"));
    	serialVersionUIDField.setInitializationString("1L");
		topLevelClass.addField(serialVersionUIDField);
		
    	List<IntrospectedColumn> allColumns = introspectedTable.getAllColumns();
    	for (IntrospectedColumn introspectedColumn : allColumns) {
    		Field field = new Field(("property_" + introspectedColumn.getJavaProperty()).toUpperCase(), FullyQualifiedJavaType.getStringInstance());
    		field.setInitializationString("\"" + introspectedColumn.getJavaProperty() +"\"");
    		field.setStatic(true);
    		field.setFinal(true);
    		field.setVisibility(JavaVisibility.PUBLIC);
    		field.setTransient(true);
    		field.addJavaDocLine("/** 字段 " + introspectedColumn.getJavaProperty() +" 的常量*/");
    		topLevelClass.addField(field);
		}
    	
        String tableName = introspectedTable.getFullyQualifiedTableNameAtRuntime();
        //如果包含空格，或者需要分隔符，需要完善
        if (StringUtility.stringContainsSpace(tableName)) {
            tableName = context.getBeginningDelimiter()
                    + tableName
                    + context.getEndingDelimiter();
        }
        //是否忽略大小写，对于区分大小写的数据库，会有用
        if (caseSensitive && !topLevelClass.getType().getShortName().equals(tableName)) {
            topLevelClass.addAnnotation("@Table(name = \"" + tableName + "\")");
        } else if (!topLevelClass.getType().getShortName().equalsIgnoreCase(tableName)) {
            topLevelClass.addAnnotation("@Table(name = \"" + tableName + "\")");
        }
        
        generateToString(introspectedTable, topLevelClass);
    }

    /**
     * 生成基础实体类
     *
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        processEntityClass(topLevelClass, introspectedTable);
        return true;
    }

    /**
     * 生成实体类注解KEY对象
     *
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        processEntityClass(topLevelClass, introspectedTable);
        return true;
    }
    
    public boolean isNeedForceConvertToLong(IntrospectedColumn introspectedColumn) {
    	String fileName = introspectedColumn.getJavaProperty();
    	return (fileName.contains("createTime")
    			|| fileName.contains("modifyTime")
    			|| fileName.contains("beginTime")
    			|| fileName.contains("finishTime")
    			|| fileName.contains("endTime")
    			|| fileName.contains("payTime") 
    			|| fileName.contains("recordCreateTime"));
    }
    
    @Override
    public boolean modelSetterMethodGenerated(Method method,
    		TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
    		IntrospectedTable introspectedTable, ModelClassType modelClassType) {
    	
    	FullyQualifiedJavaType fullyQualifiedJavaType = introspectedColumn.getFullyQualifiedJavaType();
    	String fileName = introspectedColumn.getJavaProperty();
    	if(isNeedForceConvertToLong(introspectedColumn)) {
    		method.getParameters().clear();
    		method.addParameter(new Parameter(new FullyQualifiedJavaType("java.lang.Long"), fileName));
    	}
    	
    	if(fullyQualifiedJavaType.equals(new FullyQualifiedJavaType("java.lang.Byte"))
    			|| fullyQualifiedJavaType.equals(new FullyQualifiedJavaType("java.lang.Boolean"))) {
    		method.getParameters().clear();
    		method.addParameter(new Parameter(new FullyQualifiedJavaType("java.lang.Integer"), fileName));
    	}
    	
    	if(fullyQualifiedJavaType.equals(new FullyQualifiedJavaType("java.lang.Boolean"))) {
    		method.getParameters().clear();
    		method.addParameter(new Parameter(new FullyQualifiedJavaType("java.lang.Integer"), fileName));
    	}
    	
    	
    	return super.modelSetterMethodGenerated(method, topLevelClass,
    			introspectedColumn, introspectedTable, modelClassType);
    }

    @Override
    public boolean modelGetterMethodGenerated(Method method,
    		TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
    		IntrospectedTable introspectedTable, ModelClassType modelClassType) {
    	
    	FullyQualifiedJavaType fullyQualifiedJavaType = introspectedColumn.getFullyQualifiedJavaType();
    	if(isNeedForceConvertToLong(introspectedColumn)) {
    		method.setReturnType(new FullyQualifiedJavaType("java.lang.Long"));
    	}
    	
    	if(fullyQualifiedJavaType.equals(new FullyQualifiedJavaType("java.lang.Byte"))
    			|| fullyQualifiedJavaType.equals(new FullyQualifiedJavaType("java.lang.Boolean"))) {
    		method.setReturnType(new FullyQualifiedJavaType("java.lang.Integer"));
    	}
    	
    	if(fullyQualifiedJavaType.equals(new FullyQualifiedJavaType("java.lang.Boolean"))) {
    		method.setReturnType(new FullyQualifiedJavaType("java.lang.Integer"));
    	}
    	
    	return super.modelGetterMethodGenerated(method, topLevelClass,
    			introspectedColumn, introspectedTable, modelClassType);
    }
    
    
    @Override
    public boolean modelFieldGenerated(Field field,
    		TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
    		IntrospectedTable introspectedTable, ModelClassType modelClassType) {
    	
    	if("id".equalsIgnoreCase(field.getName())) {
    		//默认是自增的
    		field.addAnnotation("@GeneratedValue(generator = \"JDBC\")");
    		field.addAnnotation("@OrderBy(\"DESC\")");
    	}
    	
    	if(isNeedForceConvertToLong(introspectedColumn)) {
    		System.out.println("该字段[" + field.getName() +"]为时间类型,转为long");
    		field.setType(new FullyQualifiedJavaType("java.lang.Long"));
    	}
    	
    	if(field.getType().equals(new FullyQualifiedJavaType("java.lang.Byte"))) {
    		System.out.println("该字段[" + field.getName() +"]生成是Byte,转为Integer");
    		field.setType(new FullyQualifiedJavaType("java.lang.Integer"));
    	}
    	
    	if(field.getType().equals(new FullyQualifiedJavaType("java.lang.Boolean"))) {
    		System.out.println("该字段[" + field.getName() +"]生成是Boolean,转为Integer");
    		field.setType(new FullyQualifiedJavaType("java.lang.Integer"));
    	}
    	
    	return super.modelFieldGenerated(field, topLevelClass, introspectedColumn,
    			introspectedTable, modelClassType);
    }
    /**
     * 生成带BLOB字段的对象
     *
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        processEntityClass(topLevelClass, introspectedTable);
        return false;
    }

    //下面所有return false的方法都不生成。这些都是基础的CRUD方法，使用通用Mapper实现
    @Override
    public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientInsertMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientInsertSelectiveMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientSelectByPrimaryKeyMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientInsertMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientInsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientSelectAllMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientSelectAllMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientSelectByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapDeleteByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapInsertElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapInsertSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapSelectAllElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapUpdateByPrimaryKeyWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean providerGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean providerApplyWhereMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean providerInsertSelectiveMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }

    @Override
    public boolean providerUpdateByPrimaryKeySelectiveMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        return false;
    }
}
